<template>
  <div class="container">
    <h1>列车实时速度监控 - {{ line }}</h1>
    <div class="status">
      <span :class="['connection-status', isConnected ? 'connected' : 'disconnected']">
        {{ isConnected ? '● 已连接' : '● 已断开' }}
      </span>
      <span class="last-update">最后更新: {{ lastUpdateTime }}</span>
    </div>
    <div class="info-panel">
      <div>日期: {{ date }}</div>
      <div>当前位置: {{ formattedPosition }}</div>
      <div>当前速度: {{ speed }} km/h</div>
      <div>信号: {{ signal }}/10</div>
    </div>
    <canvas ref="chartCanvas" width="1590" height="400"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { initSpeedChart, updateChartData } from './speedChart';

const chartCanvas = ref(null);
const isConnected = ref(false);
const lastUpdateTime = ref('');
const line = ref('线路A');
const date = ref('');
const formattedPosition = ref('');
const speed = ref(0);
const signal = ref(0);
const updateInterval = 1000 / 60; // 60fps

let ws = null;
let chartInstance = null;
let reconnectTimer;

const connectWebSocket = () => {
  try {
    if (ws) {
      ws.close();
    }

    ws = new WebSocket('ws://127.0.0.1:30000');

    ws.onopen = () => {
      console.log('WebSocket连接成功');
      isConnected.value = true;
      // 连接成功时初始化图表
      if (chartCanvas.value && !chartInstance) {
        chartInstance = initSpeedChart(chartCanvas.value);
      }
    };

    ws.onmessage = (event) => {
      try {
        const newData = JSON.parse(event.data);
        processData(newData);
      } catch (error) {
        console.error('数据解析错误:', error);
      }
    };

    ws.onclose = () => {
      console.log('WebSocket连接已关闭，准备重连...');
      isConnected.value = false;

      // 清理图表实例
      if (chartInstance) {
        chartInstance.destroy();
        chartInstance = null;
      }

      // 设置重连
      if (!reconnectTimer) {
        reconnectTimer = window.setTimeout(() => {
          reconnectTimer = null;
          connectWebSocket();
        }, 1000);
      }
    };

    ws.onerror = (error) => {
      console.error('WebSocket错误:', error);
      isConnected.value = false;
    };
  } catch (error) {
    console.error('WebSocket连接失败:', error);
    isConnected.value = false;

    // 设置重连
    if (!reconnectTimer) {
      reconnectTimer = window.setTimeout(() => {
        reconnectTimer = null;
        connectWebSocket();
      }, 1000);
    }
  }
};

const processData = (newData) => {
  const { time, speed: newSpeed, position, signal: newSignal, date: newDate, line: newLine } = newData;

  // 更新显示数据
  line.value = newLine || '未知车次';
  lastUpdateTime.value = time;
  date.value = newDate || '未知';
  formattedPosition.value = position || '未知位置';
  speed.value = newSpeed || 0;
  signal.value = parseInt(newSignal) || 0;

  // 更新图表
  if (chartInstance) {
    updateChartData(chartInstance, {
      time,
      speed: parseInt(newSpeed) || 0,
      signal: `G${parseInt(newSignal)}`,  // 添加信号信息，格式为 G1, G2 等
      position: position || '未知位置'
    });
  }
};

onMounted(() => {
  connectWebSocket();
});

onBeforeUnmount(() => {
  if (reconnectTimer) {
    clearTimeout(reconnectTimer);
    reconnectTimer = null;
  }

  if (ws) {
    ws.close();
    ws = null;
  }

  if (chartInstance) {
    chartInstance.destroy();
    chartInstance = null;
  }
});
</script>
<style scoped>
.container {
  font-family: Arial, sans-serif;
  margin: 0 auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  font-size: 25px;
}

h1 {
  color: #333;
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.status {
  margin-bottom: 15px;
  padding: 8px;
  text-align: center;
  background: #f5f5f5;
  border-radius: 4px;
  font-size: 18px;
}

.connection-status {
  font-weight: bold;
}

.connection-status.connected {
  color: green;
}

.connection-status.disconnected {
  color: red;
}

.last-update {
  margin-left: 15px;
  color: #666;
}

.info-panel {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 5px;
  font-size: 18px;
}

.info-panel div {
  padding: 10px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.chart-container {
  position: relative;
  height: 500px;
  width: 100%;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 10px;
  box-sizing: border-box;
  background: white;
}
</style>
